import 'dart:convert'; // 用于处理 JSON
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http; // 添加 http 包
import 'package:hello_world/practice_body.dart';

class MixedOperationsPage extends StatefulWidget {
  const MixedOperationsPage({super.key});

  @override
  State<MixedOperationsPage> createState() => _MixedOperationsPageState();
}

class _MixedOperationsPageState extends State<MixedOperationsPage> {
  final List<Map<String, dynamic>> _questions = [];
  final List<String> _userAnswers = [];
  final List<TextEditingController> _controllers = [];
  int _correctCount = 0;
  int _incorrectCount = 0;
  int _totalQuestions = 0;
  int _getScore = 0;

  void _updateCorrectCount(int count) {
    setState(() {
      _correctCount = count;
    });
  }

  void _updateIncorrectCount(int count) {
    setState(() {
      _incorrectCount = count;
    });
  }

  void _updateScore(int score) {
    setState(() {
      _getScore = score;
    });
  }

  Future<void> _generateQuestionsFromApi(int questionCount) async {
    const apiUrl = 'http://101.34.58.190:8080/express';
    final url = Uri.parse('$apiUrl?num=$questionCount&type=5');

    try {
      final response = await http.get(url);
      if (response.statusCode == 200) {
        final data = json.decode(response.body);

        // 提取 API 返回的数据
        final List<Map<String, dynamic>> questions = [];
        final List<TextEditingController> controllers = [];

        for (var item in data['expressVOs']) {
          questions.add({
            "examinationId": data["examinationId"], // 从外部字段获取
            "expressId": item["id"],               // 从每个题目获取
            "express": item["express"],            // 题目表达式
          });
          controllers.add(TextEditingController());
        }

        // 更新状态
        setState(() {
          _questions
            ..clear()
            ..addAll(questions);
          _controllers
            ..clear()
            ..addAll(controllers);
          _userAnswers
            ..clear()
            ..addAll(List.filled(questions.length, ''));
          _totalQuestions = questionCount;
          _correctCount = 0;
          _incorrectCount = 0;
        });
      } else {
        throw Exception('Failed to load questions');
      }
    } catch (e) {
      print('获取题目失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('无法获取题目，请检查网络连接！')),
      );
    }
  }

  void _submitAnswers() {
    setState(() {
      _correctCount = 0;
      _incorrectCount = 0;
      for (int i = 0; i < _questions.length; i++) {
        final String userAnswer = _controllers[i].text.trim();
        if (userAnswer.isNotEmpty && userAnswer == _questions[i]["answer"].toString()) {
          _correctCount++;
        } else {
          _incorrectCount++;
        }
      }
      _getScore = _correctCount * 2; // 每题得分为2分
    });
  }

  void _updateAnswer(int index, String value) {
    setState(() {
      _userAnswers[index] = value;
      _controllers[index].text = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('混合运算练习题'),
        backgroundColor: Colors.blue.shade300,
      ),
      body: PracticeBody(
        generateQuestions: _generateQuestionsFromApi,
        submitAnswers: _submitAnswers,
        questions: _questions,
        userAnswers: _userAnswers,
        totalQuestions: _totalQuestions,
        correctCount: _correctCount,
        incorrectCount: _incorrectCount,
        score: _getScore, // 传递得分
        updateAnswer: _updateAnswer, // 传递回调函数
        controllers: _controllers,
        updateCorrectCount: _updateCorrectCount, // 传入回调
        updateIncorrectCount: _updateIncorrectCount, // 传入回调
        updateScore: _updateScore, // 传入回调
      ),
    );
  }
}
